package com.mt.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.mt.RedisUtils;
import com.mt.VO.ExpectNumVO;
import com.mt.constants.SYS;
import com.mt.enums.Status;
import com.mt.exception.GlobalException;
import com.mt.utils.RedisKeyGenerator;
import com.mt.mapper.ExpectNumMapper;
import com.mt.service.ExpectNumService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author Wang
 * @Description
 * @date 2021/1/19-16:56
 */
@Slf4j
@Service
public class ExpectNumServiceImpl implements ExpectNumService {
    @Resource
    ExpectNumMapper mapper;
    @Resource
    RedisUtils redisUtils;

    @Override
    public int getExpectStatus(String userId, int filmId) {
        String itemKey = RedisKeyGenerator.getFilmKey(userId, filmId);
        if (redisUtils.hexists(SYS.EXPECT_NUM_KEY,itemKey)) {
            System.out.println("redis status"+(int) redisUtils.hget(SYS.EXPECT_NUM_KEY,itemKey));
            return (int) redisUtils.hget(SYS.EXPECT_NUM_KEY,itemKey);
        }
        ExpectNumVO watch  =mapper.selectExpectNum(userId,filmId);
        if (watch == null){
            return 0;
        }
        return watch.getStatus();
    }

    @Override
    public boolean addExpect2Redis(String userId, int filmId, int status) {
        String key = RedisKeyGenerator.getFilmKey(userId, filmId);
        return redisUtils.hset(SYS.EXPECT_NUM_KEY,key,status);
    }

    @Override
    public boolean addExpectList(List<ExpectNumVO> list) {
        return mapper.insertExpectList(list);
    }

    @Override
    public boolean modifyExpectList(List<ExpectNumVO> list) {
        return mapper.modifyExpectList(list);
    }

    @Override
    public boolean saveExpectList2Db(List<ExpectNumVO> list) {
        List<ExpectNumVO> updateList = CollUtil.newArrayList();
        List<ExpectNumVO> insertList = CollUtil.newArrayList();
        for (ExpectNumVO expect :list){
            ExpectNumVO expectNumVO = mapper.selectExpectNum(expect.getUserId(),expect.getFilmId());
            if (expectNumVO != null){
                updateList.add(expect);
            }else {
                insertList.add(expect);
            }
        }
        boolean addLikeList = this.addExpectList(insertList);
        boolean modifLikeList = this.modifyExpectList(updateList);
        if (addLikeList && modifLikeList){
            for (ExpectNumVO expect :list) {
                String key = RedisKeyGenerator.getLikeKey(expect.getUserId(), expect.getFilmId());
                log.debug("清除缓存EXPECT_NUM_KEY."+key);
                redisUtils.hdel(SYS.EXPECT_NUM_KEY,key);
            }
        }else{
            throw new GlobalException(Status.ERROR,"点赞信息缓存入库失败");
        }

        return true;
    }

    @Override
    public boolean countExpectTotalNum(Map<Integer, Integer> map) {
        return mapper.calculateExpectNum(map);
    }
}
